﻿using System.Diagnostics.CodeAnalysis;
using BootstrapBlazor.Components;
using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.Localization;
using Microsoft.JSInterop;

namespace BootstrapBlazor.Components;

/// <summary>
/// IconPicker 组件实现类
/// </summary>
public partial class IconPicker
{
    private ElementReference SelectElement { get; set; }

    /// <summary>
    /// 获得/设置 是否显示关闭按钮 默认为 true 显示
    /// </summary>
    [Parameter]
    public bool ShowCloseButton { get; set; } = true;

    /// <summary>
    /// 获得/设置 按钮颜色
    /// </summary>
    [Parameter]
    public Color Color { get; set; } = Color.None;

    /// <summary>
    /// 获得/设置 是否显示搜索框 默认为 false 不显示
    /// </summary>
    [Parameter]
    public bool ShowSearch { get; set; } = false;

    /// <summary>
    /// 获得/设置 是否显示搜索关键字
    /// </summary>
    [Parameter]
    public string SearchText { get; set; } = string.Empty;

    /// <summary>
    /// 获得 PlaceHolder 属性
    /// </summary>
    [Parameter]
    public string PlaceHolder { get; set; } = string.Empty;

    [Inject]
    [NotNull]
    private IStringLocalizer<IconPicker>? Localizer { get; set; }

    /// <summary>
    /// 获得/设置 绑定数据集
    /// </summary>
    [Parameter]
    [NotNull]
    public IEnumerable<SelectedItem> Items { get; set; } = Enumerable.Empty<SelectedItem>();

    /// <summary>
    /// 选中项
    /// </summary>
    private List<SelectedItem> SelectedItems { get; set; } = new();

    private bool IsShow { get; set; }

    private string? ClassString => CssBuilder.Default("icon-picker")
        .AddClass("show", IsShow)
        .AddClass("disabled", IsDisabled)
        .Build();

    private string? ToggleClassString => CssBuilder.Default("dropdown-menu-toggle")
        .AddClass($"border-{Color.ToDescriptionString()}", Color != Color.None && !IsDisabled)
        .AddClass("disabled", IsDisabled)
        .AddClass("selected", SelectedItems.Any())
        .AddClass(CssClass).AddClass(ValidCss)
        .Build();

    private string? PlaceHolderClassString => CssBuilder.Default("icon-picker-ph")
        .AddClass("d-none", SelectedItems.Any())
        .Build();

    /// <summary>
    /// OnInitialized 方法
    /// </summary>
    protected override void OnInitialized()
    {
        base.OnInitialized();

        PlaceHolder ??= Localizer[nameof(PlaceHolder)];
    }

    /// <summary>
    /// OnParametersSetAsync 方法
    /// </summary>
    /// <returns></returns>
    protected override async Task OnParametersSetAsync()
    {
        await base.OnParametersSetAsync();

        // 通过 Value 对集合进行赋值
        if (!string.IsNullOrWhiteSpace(CurrentValueAsString))
        {
            var vals = CurrentValueAsString.Split(',', StringSplitOptions.RemoveEmptyEntries);
            SelectedItems = Items.Where(x => vals.Contains(x.Value)).ToList();
        }
    }

    /// <summary>
    /// OnAfterRenderAsync 方法
    /// </summary>
    /// <param name="firstRender"></param>
    /// <returns></returns>
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);

        if (firstRender)
        {
            Interop = new JSInterop<IconPicker>(JSRuntime);
            await Interop.InvokeVoidAsync(this, SelectElement, "bb_icon_picker", nameof(Close));
        }
    }

    /// <summary>
    /// 客户端关闭下拉框方法
    /// </summary>
    [JSInvokable]
    public void Close()
    {
        IsShow = false;
        StateHasChanged();
    }

    /// <summary>
    /// 展开/收缩 下拉框方法
    /// </summary>
    protected void ToggleMenu()
    {
        if (!IsDisabled)
        {
            IsShow = !IsShow;
        }
    }

    /// <summary>
    /// 控制图标 选中/取消选中 方法
    /// </summary>
    /// <param name="item"></param>
    /// <returns></returns>
    protected Task ToggleItem(SelectedItem item)
    {
        if (!IsDisabled)
        {
            if (SelectedItems.Contains(item))
            {
                SelectedItems.Remove(item);
            }
            else
            {
                if (SelectedItems.Count > 0)
                    SelectedItems.Clear();

                SelectedItems.Add(item);
            }

            CurrentValueAsString = string.Join(",", SelectedItems.Select(x => x.Value));

            StateHasChanged();
        }
        return Task.CompletedTask;
    }

    /// <summary>
    /// 重置搜索按钮调用此方法
    /// </summary>
    protected async Task ClearSearchClick()
    {
        SearchText = string.Empty;
        await OnQueryAsync();
    }

    /// <summary>
    /// 查询按钮调用此方法
    /// </summary>
    /// <returns></returns>
    protected Task OnQueryAsync()
    {
        if (!string.IsNullOrWhiteSpace(SearchText))
        {
            Items = Items.Where(x =>
                x.Text.Contains(SearchText) ||
                x.Value.Contains(SearchText) ||
                x.GroupName.Contains(SearchText));
        }

        StateHasChanged();
        return Task.CompletedTask;
    }

    private JSInterop<IconPicker>? Interop { get; set; }

    /// <summary>
    /// 客户端检查完成时调用此方法
    /// </summary>
    /// <param name="valid"></param>
    protected override void OnValidate(bool? valid)
    {
        Color = valid == true ? Color.Success : Color.Danger;
    }

    /// <summary>
    /// Dispose 方法
    /// </summary>
    /// <param name="disposing"></param>
    protected virtual void Dispose(bool disposing)
    {
        if (disposing && Interop != null)
        {
            Interop.Dispose();
            Interop = null;
        }
    }

    /// <summary>
    /// Dispose 方法
    /// </summary>
    public void Dispose()
    {
        Dispose(disposing: true);
        GC.SuppressFinalize(this);
    }
}
